
from rest_framework.views import APIView,Response
from users.models import UserModel
from orders.models import Order,OrderGoods
from shops.models import Shops,Kind,Dishes
from shops.serializer import ShopsModelSer,KindModelSer,DishesModelSer

from django.db.models import Q
from django.db import models    #与Q查询一起用

from utils.jwt_token import generate_token
from utils.force_login import check_login

from qiniu import Auth


# 注册商家
class Shops_register(APIView):
    @check_login
    def post(self,request):
        shops_name = request.data.get('shops_name')
        shops_mobile = request.data.get('shops_mobile')
        shops_address = request.data.get('shops_address')
        sending_fee = request.data.get('sending_fee')
        print('接收用户注册商家信息',shops_name,shops_mobile,shops_address,sending_fee)

        user = request.user.id
        print('注册商家的用户',user.id)
        if all([shops_name,shops_mobile,shops_address,sending_fee]):
            try:
                Shops.objects.get(shops_name=shops_name)
                return Response({'code': 204, 'msg': '商家名已被注册'})
            except Exception as e:
                print('查询商家错误',e)
            Shops.objects.create(shops_name=shops_name,shops_mobile=shops_mobile,
                        shops_address=shops_address,sending_fee=sending_fee,user_id=user.id)
            return Response({'code': 200, 'msg': '注册商家成功'})
        return Response({'code': 204, 'msg': '注册商家信息不全'})



# 商家登录
class Shops_Login(APIView):
    def post(self,request):
        account = request.data.get('account')
        password = request.data.get('password')
        print('接收商家登录信息',account,password)

        if all([account,password]):
            user = UserModel.objects.get(models.Q(account=account) | models.Q(mobile=account))
            print('哈哈哈哈',user.account,type(user))
            if user.password == password:
                shops_user = user.shops_set.all()
                shops=ShopsModelSer(shops_user,many=True)
                print('是否是商家',shops_user)
                if not shops_user:
                    return Response({'code': 204, 'msg': '你还不是商家，请先普通用户登录,再申请商家'})
                token = generate_token(user)
                data_ = {
                    'id':user.id,
                    'account':user.account,
                    'token':token,
                }
                print('登陆成功,返回token',token)
                return Response({'code': 200, 'msg': '欢迎商家登录','user_info':data_})
            else:
                return Response({'code': 204, 'msg': '密码不正确'})
        else:
            return Response({'code': 204, 'msg': '信息不完整'})



# 商家信息管理
class ShopsView_get(APIView):
    # 获取所有商家信息
    def get(self,request):
        try:
            shops_set = Shops.objects.all()
            print('获取所有商家信息', shops_set)
            shops_set = ShopsModelSer(shops_set,many=True)
            return Response({'code': 200, 'msg': '获取所有商家信息成功', 'data': shops_set.data})
        except Exception as e:
            print('失败',e)
            return Response({'code': 204, 'msg': '获取所有商家信息失败'})

    @check_login  # 修改商家信息
    def put(self, request):
        print('sadas', request.user.id)
        shops_name = request.data.get('shops_name')
        shops_mobile = request.data.get('shops_mobile')
        shops_slogan = request.data.get('shops_slogan')
        shops_address = request.data.get('shops_address')
        sending_fee = request.data.get('sending_fee')
        id = request.user.id
        print('接受修改的数据', shops_name, shops_mobile)
        try:
            Shops.objects.filter(user_id=id).update(shops_name=shops_name,
                                                    shops_mobile=shops_mobile, shops_slogan=shops_slogan,
                                                    shops_address=shops_address, sending_fee=sending_fee)
            return Response({'code': 200, 'msg': '修改商家信息成功'})
        except Exception as e:
            print('修改登录商家信息失败', e)
            return Response({'code': 204, 'msg': '修改商家信息失败'})


#获取商家信息
class Shop_get_id(APIView):

    def get(self,request,pk):
        try:
            shops = Shops.objects.get(user_id=pk)
            print('获取的商家信息', shops)
            shops_set = ShopsModelSer(shops)
            return Response({'code': 200, 'msg': '获取商家信息成功', 'shops_list': shops_set.data})
        except Exception as e:
            print('失败',e)
            return Response({'code': 204, 'msg': '获取商家信息失败'})





# 菜品种类
class KindView(APIView):
    #获取所有菜品种类
    @check_login
    def get(self,request):
        id = request.user.id
        try:
            shops = Shops.objects.get(id=id)
            print('这是获取的商家',shops)
        except Exception as e:
            print('获取商家失败', e)
            return Response({'code': 204, 'msg': '这个商家不存在'})

        try:
            shops_kind_set = Kind.objects.filter(shops_id=shops.id)
            kind_all = KindModelSer(shops_kind_set, many=True)
            return Response({'code': 200, 'msg': '获取商家所有菜品种类成功', 'kind_all': kind_all.data})
        except Exception as e:
            print('失败', e)
            return Response({'code': 204, 'msg': '获取商家所有菜品种类失败'})


    @check_login    #添加种类
    def post(self,request):
        kind_name = request.data.get('kind_name')

        id = request.user.id
        shops = Shops.objects.get(user_id=id)
        # print('这是获取的商家',shops)
        try:
            Kind.objects.create(kind_name=kind_name,shops_id=shops.id)
            return Response({'code':200,'msg':'商家添加菜品种类成功'})
        except Exception as e:
            print('失败',e)
            return Response({'code':204,'msg':'商家添加菜品种类失败'})


# class Kind_put(APIView):
    # @check_login    #修改种类信息
    # def put(self,request,pk):
    #     kind_name = request.data.get('kind_name')
    #     print('这是要修改的种类信息',pk,kind_name)
    #     try:
    #         shops = Shops.objects.get(user_id=request.user.id)
    #     except Exception as e:
    #         print('获取商家失败', e)
    #         return Response({'code': 204, 'msg': '您不是商家'})
    #     try:
    #         Kind.objects.filter(id=pk,shops_id=shops.id).update(kind_name=kind_name)
    #         return Response({'code': 200, 'msg': '商家修改菜品种类成功',})
    #     except Exception as e:
    #         print('商家修改菜品种类失败', e)
    #         return Response({'code': 204, 'msg': '商家修改菜品种类失败'})
    #
    #
    # @check_login    #删除种类
    # def delete(self,request,pk):
    #     try:
    #         shops = Shops.objects.get(user_id=request.user.id)
    #         try:
    #             Kind.objects.get(Q(id=pk) & Q(shops_id=shops.id))
    #         except Exception as e:
    #             print('商家删除种类失败',e)
    #             return Response({'code':204,'msg':'该商家无此菜品种类,删除失败'})
    #         Kind.objects.filter(id=pk,shops_id=shops.id).delete()
    #         return Response({'code': 200, 'msg': '商家删除种类成功'})
    #     except Exception as e:
    #         print('获取商家失败', e)
    #         return Response({'code': 204, 'msg': '您不是商家,商家不存在'})



class DishesView(APIView):
    # 菜品信息管理
    @check_login
    def get(self,request,pk):
        try:
            shops = Shops.objects.get(id=request.user.id)
            print('这是获取的商家',shops)
        except Exception as e:
            return Response({'code': 204, 'msg':'该商家不存在'})
        try:
            if pk==7:
                dishes_set = Dishes.objects.filter(shops_id=shops.id)
                data = []
                for i in dishes_set:
                    print('>>>>>>', i.kind_id)
                    kind = Kind.objects.get(id=i.kind_id)
                    data_ = {
                        'id':i.id,
                        'kind_id': kind.id,
                        'kind_name': kind.kind_name,
                        'dishes_name': i.dishes_name,
                        'dishes_price': i.dishes_price,
                        'dishes_picture': i.dishes_picture,
                    }
                    data.append(data_)
                return Response({'code': 200, 'msg': '获取商家菜品所有菜品成功', 'kind_dishes': data})
            else:
                kind_dishes_set = Dishes.objects.filter(Q(shops_id=request.user.id) & Q(kind_id=pk))
                data = []
                for i in kind_dishes_set:
                    print('>>>>>>', i.kind_id)
                    kind = Kind.objects.get(id=i.kind_id)
                    data_ = {
                        'id':i.id,
                        'kind_id': kind.id,
                        'kind_name': kind.kind_name,
                        'dishes_name': i.dishes_name,
                        'dishes_price': i.dishes_price,
                        'dishes_picture': i.dishes_picture,
                    }
                    data.append(data_)
                return Response({'code': 200, 'msg': '获取商家一个种类所有菜品成功', 'kind_dishes':data})
        except Exception as e:
            return Response({'code': 204, 'msg': '获取商家种类菜品所有菜品失败'})



class Dishes_all(APIView):
    #获取商家所有菜品
    @check_login
    def get(self,request):
        id = request.user.id
        try:
            shops = Shops.objects.get(id=id)
            print('这是获取的商家',shops)
        except Exception as e:
            print('获取登录商家失败', e)
            return Response({'code': 204, 'msg':'该商家不存在'})
        try:
            dishes_set = Dishes.objects.filter(shops_id=shops.id)
            print('商家所有菜品', dishes_set)
            data = []
            for i in dishes_set:
                print('>>>>>>',i.kind_id)
                kind = Kind.objects.get(id=i.kind_id)
                data_={
                    'id':i.id,
                    'kind_id':kind.id,
                    'kind_name':kind.kind_name,
                    'dishes_name':i.dishes_name,
                    'dishes_price':i.dishes_price,
                    'dishes_picture':i.dishes_picture,
                }
                data.append(data_)
            return Response({'code': 200, 'msg': '获取商家菜品所有菜品成功', 'dishes_all':data})
        except Exception as e:
            print('获取商家菜品所有菜品失败', e)
            return Response({'code': 204, 'msg': '获取商家菜品所有菜品失败'})


    @check_login  # 添加菜品
    def post(self, request):
        dishes_name = request.data.get('dishes_name')
        dishes_price = request.data.get('dishes_price')
        dishes_picture = request.data.get('dishes_picture')
        kind_id = request.data.get('kind_id')
        # id = request.user.id
        print('添加菜品的数据', dishes_name, dishes_price, dishes_picture, kind_id)
        try:
            shops = Shops.objects.get(user_id=request.user.id)
        except Exception as e:
            print('获取登录商家失败', e)
            return Response({'code': 204, 'msg': '您还不是商家,无法添加菜品'})
        try:
            dishes_name = Dishes.objects.get(dishes_name=dishes_name)
            return Response({'code': 204, 'msg': '该菜品已存在,无法添加'})
        except Exception as e:
            print('商家添加菜品失败', e)
            try:
                Dishes.objects.create(dishes_name=dishes_name, dishes_price=dishes_price,
                                      kind_id=kind_id, shops_id=shops.id,dishes_picture=dishes_picture)
                return Response({'code': 200, 'msg': '商家添加菜品成功'})
            except Exception as e:
                print('商家添加菜品失败', e)
                return Response({'code': 204, 'msg': '商家添加菜品失败'})



class Dishes_particulars(APIView):
    # 获取一个菜品详情
    def get(self,request,pk):
        shops_id = request.data.get('shops_id')
        print('获取的商家id',shops_id)
        try:
            dishes = Dishes.objects.get(models.Q(id=pk) & models.Q(shops_id=shops_id))
            dishes_ser = DishesModelSer(dishes)
            return Response({'code': 200, 'msg': '获取一个菜品成功', 'data':dishes_ser.data})
        except Exception as e:
            print('获获一个菜品失败', e)
            return Response({'code': 204, 'msg': '该商家无此菜品'})


    @check_login  # 商家修改菜品信息
    def put(self, request, pk):
        dishes_name = request.data.get('dishes_name')
        dishes_price = request.data.get('dishes_price')
        dishes_picture = request.data.get('dishes_picture')
        kind_id = request.data.get('kind_id')
        print('修改菜品的数据', dishes_name, kind_id)
        try:
            Dishes.objects.filter(id=pk).update(dishes_name=dishes_name,
                                                dishes_price=dishes_price, kind_id=kind_id,
                                                dishes_picture=dishes_picture)
            return Response({'code': 200, 'msg': '修改菜品信息成功'})
        except Exception as e:
            print(e)
            return Response({'code': 204, 'msg': '商家修改菜品失败'})

    @check_login  # 商家删除菜品
    def delete(self, request, pk):
        try:
            shops = Shops.objects.get(user_id=request.user.id)
        except Exception as e:
            print('获取登录商家失败', e)
            return Response({'code': 204, 'msg': '您不是商家'})

        try:
            Dishes.objects.get(Q(id=pk) & Q(shops_id=shops.id))
            Dishes.objects.get(id=pk).delete()
            return Response({'code': 200, 'msg': '商家删除菜品成功'})
        except Exception as e:
            print('获取菜品失败', e)
            return Response({'code': 204, 'msg': '您没有这道菜菜品'})


# 获取商家下所有完成的订单
class Shops_order(APIView):
    @check_login
    def get(self,request):
        shops_id = request.user.id
        print('商家id',shops_id)
        order = Order.objects.filter(shop_id=shops_id,pay_status=2).all()
        order_list = []
        for i in order:
            data_ = {
                'shop_id': i.shop_id,
                'order_id': i.order_id,
                'order_num': i.total_count,
                'order_price': i.total_amount,
            }
            order_dishes = OrderGoods.objects.filter(order_id=i.order_id).all()
            dishes_list = []
            for j in order_dishes:
                data = {
                    'name': j.dishes.dishes_name,
                    'price': j.price,
                    'num': j.count,
                    'img': j.dishes.dishes_picture
                }
                dishes_list.append(data)
            data_['order_dishes'] = dishes_list
            user_info = []
            user = UserModel.objects.filter(id=i.user_id).all()
            for i in user:
                info = {
                    'id':i.id,
                    'nickname':i.nickname,
                    'profile_photo':i.profile_photo
                }
                user_info.append(info)
            data_['user_info'] = user_info
            order_list.append(data_)
        return Response(
            {'message': '获取成功', 'code': 200, 'order': order_list})



# AK='Qx6yau9NHEOUSbQMu57d9h9SpoFfn1vPFHGyu5kP'
# SK='KNzyLZVipYvjxLtR91Op0iN5kMFLn_QzCZ0t2a08'

AK='ZJrTu7uZ7usufrezcxuyRvXko-qIVGh-DlMkCTht'
SK='Y5HsOmq9gky9pNzB2Loe3b_m8DnFKsV9T6aQD8ms'



def qiniu_token():
    q = Auth(AK,SK)
    bucket = 'cqf032'
    token = q.upload_token(bucket)
    print('获取七牛token',token)
    return token



class Qiniu_Token(APIView):
    def get(self,request):
        toekn = qiniu_token()
        return Response({'code':200,'msg':"获取七牛token成功",'data':toekn})
